package com.zhiyou.app.shop.manager.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiyou.app.shop.common.AycshopException;
import com.zhiyou.app.shop.common.ShopManageConstants;
import com.zhiyou.app.shop.common.util.FileUtil;
import com.zhiyou.app.shop.common.util.Page;
import com.zhiyou.app.shop.common.util.PropertiesUtil;
import com.zhiyou.app.shop.common.util.ServiceUtil;
import com.zhiyou.app.shop.manager.dao.IDeliveryAddressDao;
import com.zhiyou.app.shop.manager.dao.IGoodsCategoryDao;
import com.zhiyou.app.shop.manager.dao.ITaskLockDao;
import com.zhiyou.app.shop.manager.dao.IUserDao;
import com.zhiyou.app.shop.manager.dao.pojo.DeliveryAddress;
import com.zhiyou.app.shop.manager.dao.pojo.GoodsCategory;
import com.zhiyou.app.shop.manager.dao.pojo.TaskLock;
import com.zhiyou.app.shop.manager.dao.pojo.UserDetail;
import com.zhiyou.app.shop.manager.service.ISysManageService;

@Service
public class SysManageServiceImpl implements ISysManageService{
	@Autowired
	private IUserDao userDao;
	@Autowired
	private IGoodsCategoryDao goodsCatDao;
	@Autowired
	private IDeliveryAddressDao deliveryDao;
	@Autowired
	private ITaskLockDao taskLockDao;
	/****************************************用户管理**************************************************/
	public void saveOrUpdateUser(UserDetail user) {
		if(user.getId()==null){
			//先判断登录名是否已存在
			List list = userDao.findByProperty("loginName", user.getLoginName());
			if(null != list && list.size() > 0) throw new AycshopException("shopManage.userLoginName.replicate");
			user.setPassword("12345");
			user.setCreateDate(new Date());
			userDao.save(user);
		}else{
			UserDetail entity = this.findUserById(user.getId());
			String[] ignoreProperties = {"id","loginName","password","createDate","isDelete"};
			BeanUtils.copyProperties(user, entity,ignoreProperties);
			userDao.update(entity);
		}
	}
	
	public void getUsersByPage(Page page, UserDetail ud,Order order) {
		DetachedCriteria dc = ServiceUtil.getADetachedCriteria(UserDetail.class);
		dc.add(Restrictions.eq("isDelete", Boolean.FALSE));
		userDao.findByCriteria(page, dc, order);
	}

	public void deleteUser(String ids) {

		userDao.logicBatchDeleteByIds(ids);
	}

	public UserDetail findUserById(String id) {
		
		return userDao.findById(id);
	}

	public UserDetail loginAuth(String loginName, String password) {
		UserDetail ud = new UserDetail();
		ud.setLoginName(loginName);
		ud.setPassword(password);
		List<UserDetail> list = userDao.findByExample(ud);
		if(null == list || list.size()<1){
			throw new AycshopException("shopManage.login.failed");
		}
		return list.get(0);
	}

	/****************************************商品分类管理**************************************************/
	
	public void saveOrUpdateCategory(GoodsCategory cat) {
//		List list = goodsCatDao.findByProperty("name", cat.getName());
		
		DetachedCriteria dc = DetachedCriteria.forClass(GoodsCategory.class);
		dc.add(Restrictions.eq("name", cat.getName()));
		if(StringUtils.isNotBlank(cat.getId())){
			dc.add(Restrictions.ne("id", cat.getId()));
		}
		List list = goodsCatDao.findByCriteria(dc, null);
		if(null != list && list.size() > 0) throw new AycshopException("shopManage.goodsCategoryName.replicate");
		
		if(StringUtils.isBlank(cat.getId())){
			//上传图片
			String imgPath = this.uploadImg(cat);
			cat.setImgPath(imgPath);
			
			cat.setCreateDate(new Date());
			goodsCatDao.save(cat);
		}else{
			GoodsCategory pojo = goodsCatDao.findById(cat.getId());
			//如果图片被修改过
			String oldImgPath = null;
			if(cat.getGoodsCategoryImg() != null){
				String imgPath = this.uploadImg(cat);
				cat.setImgPath(imgPath);
				oldImgPath = pojo.getImgPath();
			}
			String[] ignoreProperties = {"id","createDate","isDelete"};
			BeanUtils.copyProperties(cat, pojo,ignoreProperties);
			goodsCatDao.update(pojo);
			
			if(null != oldImgPath) {//删除老图片
				String realpath = PropertiesUtil.getSysProperties("upload.img.basepath")+"/"+oldImgPath;
				File file = new File(realpath);
				FileUtil.deleteFiles(file);
			}
		}
	}

	private String uploadImg(GoodsCategory cat){
		String imgPath = FileUtil.aycShopUpload(cat.getGoodsCategoryImg(), 
							cat.getGoodsCategoryImgFileName(), ShopManageConstants.GOODSCATEGORYIMGFORDER);
		return imgPath;
	}
	public void getCategoryBypage(Page page, GoodsCategory cat, Order order) {
		DetachedCriteria dc = ServiceUtil.getADetachedCriteria(GoodsCategory.class);
		dc.add(Restrictions.eq("isDelete", Boolean.FALSE));
		goodsCatDao.findByCriteria(page, dc, order);
	}

	public void deleteCats(String ids) {
		goodsCatDao.logicBatchDeleteByIds(ids);
	}

	public GoodsCategory findCatById(String id) {
		return goodsCatDao.findById(id);
	}

	public Integer getGoodsCatMaxOrder() {
		int number = goodsCatDao.getMaxOrderNumber();
		return number+1;
	}

	public List<GoodsCategory> getAllGoodsCats() {
		DetachedCriteria dc = ServiceUtil.getADetachedCriteria(GoodsCategory.class);
		dc.add(Restrictions.eq("isDelete", Boolean.FALSE));
		return goodsCatDao.findByCriteria(dc, Order.desc("orderNumber"));
	}

	public void saveDeliveryAddress(DeliveryAddress deliveryAddress) {
		//先查找该用户是否已添加收货地址
		List<DeliveryAddress> list = deliveryDao.findByProperty("userDetail.id", deliveryAddress.getUserDetail().getId());
		if(list.isEmpty()){
			deliveryDao.save(deliveryAddress);
		}else{
			DeliveryAddress pojo = list.get(0);
			pojo.setAddress(deliveryAddress.getAddress());
			deliveryDao.update(pojo);
		}
	}


	public TaskLock findByTaskName(String taskName) {
		List<TaskLock> list = taskLockDao.findByProperty("name", taskName);
		if(null != list && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	public void saveOrUpdateTaskLock(TaskLock taskLock) {
		if(null == taskLock.getId()){
			taskLockDao.save(taskLock);
		}else{
			taskLockDao.update(taskLock);
		}
	}
	
	
}
